# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
    from urllib import urlencode
    from urllib2 import Request, urlopen
except ImportError:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

import base64
import pickle
import random
import string
import time
from lib.ShowapiRequest import ShowapiRequest
from PIL import Image
import os
import logging
import datetime
import logging.handlers


def get_code(driver, id):
    # 以时间来命名截屏图片
    t = time.time()
    path = os.path.dirname(os.path.dirname(__file__)) + '\\screenshot'
    picture_name1 = path + '\\' + str(t) + '.png'
    driver.save_screenshot(picture_name1)  #截屏的图片

    # 定位坐标，找出验证码图片
    kt = driver.find_element_by_id(id)
    # print(kt.location)
    left = kt.location['x']
    top = kt.location['y']
    right = left + kt.size['width']
    lower = top + kt.size['height']

    # PIL模块的应用，抠图
    im = Image.open(picture_name1)
    img = im.crop((left, top, right, lower))
    t = time.time()
    # path = os.path.dirname(os.path.dirname(__file__)) + '\\screenshot'
    picture_name2 = path + '\\' + str(t) + '.png'
    img.save(picture_name2) #验证码的图片

# 把图片转成base64位
    f = open(picture_name2, 'rb')  # 第一个参数图像路径
    ls_f = base64.b64encode(f.read())
    f.close()

    # 调用第三方接口识别验证码
# 万维亿源的接口
    # r = ShowapiRequest("http://route.showapi.com/184-4", "272526", "a924d4e982ae404b4d1c7784f2")
    # r.addFilePara("image", picture_name2)
    # r.addBodyPara("typeId", "34")
    # r.addBodyPara("convert_to_jpg", "0")
    # r.addBodyPara("needMorePrecise", "0")
    # res = r.post()

    # # 取到具体的数字
    # code  = res.json()['showapi_res_body']['Result']
    # return code # 返回信息


# 腾讯的接口
    # 云市场分配的密钥Id
    secretId = "AKID8acvv5hcm2ja4bdyu76vks09ec6k6hdftEb7"
    # 云市场分配的密钥Key
    secretKey = "57qlyz9s2833y4uk088r6q7qqP9raw4mgm9rncU5"
    source = 'market'

    # 签名
    datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
    signStr = "x-date: %s\nx-source: %s" % (datetime, source)
    sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
    auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (
    secretId, sign.decode('utf-8'))

    # 请求方法
    method = 'POST'
    # 请求头
    headers = {
        'X-Source': source,
        'X-Date': datetime,
        'Authorization': auth,
    }
    # 查询参数
    queryParams = {
    }
    # body参数（POST方法下存在）
    bodyParams = {
        'number': '4',
        'pri_id': 'ne',
        'v_pic': ls_f}
    # url参数拼接
    url = 'http://service-98wvmcga-1256810135.ap-guangzhou.apigateway.myqcloud.com/release/yzm'
    if len(queryParams.keys()) > 0:
        url = url + '?' + urlencode(queryParams)

    request = Request(url, headers=headers)
    request.get_method = lambda: method
    if method in ('POST', 'PUT', 'PATCH'):
        request.data = urlencode(bodyParams).encode('utf-8')
        request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    response = urlopen(request, context=ctx)
    content = response.read()
    if content:
        con = eval(content.decode('utf-8'))
        return con['v_code']


# 生成日志
def get_logger():
    path = os.path.dirname(os.path.dirname(__file__)) + '\\logs'

    logger = logging.getLogger('mylogger')
    logger.setLevel(logging.DEBUG)

    rf_handle = logging.handlers.TimedRotatingFileHandler(path+'\\'+'all.log', when='midnight', interval=1, backupCount=7,
                                                          atTime=datetime.time(0, 0, 0, 0), encoding='utf-8')
    rf_handle.setFormatter(logging.Formatter('%(asctime)s-%(levelname)s-%(message)s'))

    f_handle = logging.FileHandler(path+'\\'+'error.log', encoding='utf-8')
    f_handle.setLevel(logging.ERROR)
    f_handle.setFormatter(logging.Formatter('%(asctime)s-%(levelname)s-%(filename)s[:%(lineno)d]-%(message)s'))

    logger.addHandler(rf_handle)
    logger.addHandler(f_handle)
    return logger


# 生成随机字符串
def gen_random_str():
    rand_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    return rand_str


def save_cookie(driver, path):
    with open(path, 'wb') as filehander:
        cookies = driver.get_cookies()
        print(cookies)
        pickle.dump(cookies, filehander)


def load_cookie(driver, path):
    with open(path, 'rb') as cookiesfile:
        cookies = pickle.load(cookiesfile)
        for cookie in cookies:
            driver.add_cookie(cookie)